<template>
  <div class="dict-management">
    <v-card class="elevation-10 rounded-xl pa-2">
      <v-card-title class="d-flex align-center">
        <span>字典管理</span>
        <v-spacer></v-spacer>
        <v-btn v-if="$perms('system_dict_insert')" color="primary" @click="handleInsert">
          <v-icon start>mdi-plus</v-icon>
          添加
        </v-btn>
      </v-card-title>

      <v-card-text>
        <!-- 查询表单 -->
        <v-row class="mb-4">
          <v-col cols="12" md="4">
            <v-text-field v-model="queryForm.typeCode_EQ" label="字典类型编号" placeholder="请输入字典类型编号" clearable
              variant="outlined" density="compact"></v-text-field>
          </v-col>
          <v-col cols="12" md="4">
            <v-text-field v-model="queryForm.typeName_LIKE" label="字典类型名称" placeholder="请输入字典类型名称" clearable
              variant="outlined" density="compact"></v-text-field>
          </v-col>
          <v-col cols="12" md="4" class="d-flex align-center">
            <v-btn color="primary" @click="queryData">
              <v-icon start>mdi-magnify</v-icon>
              查询
            </v-btn>
          </v-col>
        </v-row>

        <!-- 数据表格 -->
        <v-data-table :headers="headers" :items="list" :loading="listLoading" 
          :items-per-page="10" :items-per-page-options="[10, 20, 50, 100]"
          class="elevation-9 rounded-lg" loading-text="正在加载..." no-data-text="暂无数据" 
          @click:row="setSelectRows">
          <!-- 是否内置列 -->
          <template v-slot:item.izLock="{ item }">
            <v-chip :color="item.izLock === '0' ? 'success' : 'info'" size="small" variant="flat">
              {{ $getDictNameByValue('no_yes', item.izLock) }}
            </v-chip>
          </template>

          <!-- 操作列 -->
          <template v-slot:item.actions="{ item }">
            <div class="d-flex gap-2">
              <v-btn v-if="$perms('system_dict_update')" size="small" variant="text" color="primary"
                @click.stop="handleUpdate(item)">
                编辑
              </v-btn>

              <v-menu>
                <template v-slot:activator="{ props }">
                  <v-btn size="small" variant="text" v-bind="props" append-icon="mdi-chevron-down">
                    更多
                  </v-btn>
                </template>
                <v-list>
                  <v-list-item v-if="$perms('system_dict_setDict')" @click="setDict(item)">
                    <v-list-item-title>设置字典</v-list-item-title>
                  </v-list-item>
                  <v-list-item v-if="$perms('system_dict_delete')" @click="handleDelete(item)">
                    <v-list-item-title>删除</v-list-item-title>
                  </v-list-item>
                </v-list>
              </v-menu>
            </div>
          </template>
        </v-data-table>
      </v-card-text>
    </v-card>

    <!-- 编辑对话框 -->
    <Edit ref="editRef" @fetchData="fetchData" />

    <!-- 字典详情 -->
    <DictDetail ref="dictDetailRef" />
  </div>
</template>

<script setup>
import { ref, onMounted, getCurrentInstance } from 'vue';
import { getList, doDelete } from '@/api/system/dict/dictManagement';
import { isNull } from '@/utils/validate';
import { useMessage } from '@/composables/useMessage';
import { useConfirm } from '@/composables/useConfirm';
import DictDetail from './components/dictDetail.vue';
import Edit from './components/dictManagementEdit.vue';

const { proxy } = getCurrentInstance();
const { success: showSuccess, error: showError } = useMessage();
const { confirmDelete } = useConfirm();

// 响应式数据
const list = ref([]);
const listLoading = ref(true);
const total = ref(0);
const currentRow = ref(null);

// 查询表单
const queryForm = ref({
  typeCode_EQ: '',
  typeName_LIKE: ''
});

// 表格头部配置
const headers = ref([
  {
    title: '字典类型编号',
    key: 'typeCode',
    align: 'start',
    sortable: false,
    width: '200px'
  },
  {
    title: '字典类型名称',
    key: 'typeName',
    align: 'start',
    sortable: false,
    width: '200px'
  },
  {
    title: '是否内置',
    key: 'izLock',
    align: 'center',
    sortable: false,
    width: '120px'
  },
  {
    title: '备注',
    key: 'remark',
    align: 'start',
    sortable: false
  },
  {
    title: '操作',
    key: 'actions',
    align: 'center',
    sortable: false,
    width: '160px'
  }
]);

// 组件引用
const editRef = ref();
const dictDetailRef = ref();

onMounted(() => {
  fetchData();
});

/**
 * 设置字典
 */
const setDict = (row) => {
  currentRow.value = row;
  dictDetailRef.value?.show(row);
};

/**
 * 设置选中行
 */
const setSelectRows = (event, item) => {
  currentRow.value = item.item;
};

/**
 * 添加字典
 */
const handleInsert = () => {
  editRef.value?.showEdit();
};

/**
 * 编辑字典
 */
const handleUpdate = (row) => {
  if (row.id) {
    editRef.value?.showEdit(row);
  }
};

/**
 * 删除字典
 */
const handleDelete = async (row) => {
  if (row.id) {
    try {
      const confirmed = await confirmDelete(`您确定要删除字典类型"${row.typeName}"吗？此操作不可撤销。`);

      if (confirmed) {
        const response = await doDelete({ id: row.id });
        showSuccess(response.msg || '删除成功');
        await fetchData();
      }
    } catch (error) {
      console.error('删除失败:', error);
      showError('删除失败');
    }
  }
};

/**
 * 查询数据
 */
const queryData = () => {
  fetchData();
};

/**
 * 获取数据
 */
const fetchData = async () => {
  listLoading.value = true;
  try {
    // 设置大的pageSize获取全部数据，用于客户端分页
    const params = {
      pageNo: 1,
      pageSize: 1000, // 设置足够大的数量获取全部数据
      typeCode_EQ: queryForm.value.typeCode_EQ,
      typeName_LIKE: queryForm.value.typeName_LIKE
    };
    
    const { data } = await getList(params);
    if (data) {
      list.value = data.rows || [];
      total.value = data.total || 0;
    }
  } catch (error) {
    console.error('获取数据失败:', error);
    showError('获取数据失败');
  } finally {
    setTimeout(() => {
      listLoading.value = false;
    }, 300);
  }
};
</script>

<style scoped>
.dict-management {
  padding: 0;
}
</style>
